package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleConfigService;
import com.heima.common.constants.ArticleConstants;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.search.vos.SearchArticleVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author shiminghui
 * @date 2024/12/4 21:22
 * @description: TODO
 */
@Service
@Slf4j
public class ApArticleConfigServiceImpl implements ApArticleConfigService {
    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    private KafkaTemplate kafkaTemplate;
    @Autowired
    private ApArticleMapper apArticleMapper;

    /**
     * 更新文章配置
     *
     * @param map
     */
    @Override
    public void updateByMap(Map map) {
        Long articleId = (Long) map.get("articleId");
        Integer enable = (Integer) map.get("enable");
        if (articleId == null) {
            return;
        }
        boolean isDown = true;
        if (enable == 1) {
            isDown = false;
        }
        int update = apArticleConfigMapper.update(null, Wrappers.<ApArticleConfig>lambdaUpdate()
                .eq(ApArticleConfig::getArticleId, articleId)
                .set(ApArticleConfig::getIsDown, isDown));

        if (update <= 0) {
            log.error("更新文章配置失败,文章id为{}", articleId);
        }

        // 将文章配置更新到es中
        if (isDown) {
            // 下架文章,删除es中的数据
            kafkaTemplate.send(ArticleConstants.ARTICLE_ES_DOWN_TOPIC, articleId.toString());
        } else {
            // 查询文章数据
            ApArticle apArticle = apArticleMapper.selectOne(Wrappers.<ApArticle>lambdaQuery().eq(ApArticle::getId, articleId));
            if (apArticle == null) {
                log.error("文章上下架时 文章不存在");
                return;
            }
            SearchArticleVo searchArticleVo = new SearchArticleVo();
            BeanUtils.copyProperties(apArticle, searchArticleVo);
            // 上架,相当于新增
            kafkaTemplate.send(ArticleConstants.ARTICLE_ES_SYNC_TOPIC, JSON.toJSONString(searchArticleVo));
        }
    }
}
